#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
@Author: zhuo
@Software: PyCharm
@File: tAxfHelper.py
@Time: 2025/8/5
@Function: ctAxfHelper:AXF文件解析模块
"""
import struct
from elftools.elf.elffile import ELFFile
from elftools.dwarf.locationlists import LocationParser


class ctAxfHelper:
    def __init__(self, file_path):
        """
        function:  初始化AXF文件解析器
              in:  file_path: AXF文件路径
             out:  None
          return:  None
          others: Initialize AXF file parser
        """
        self.file_path = file_path
        self.elf_file = None
        self.dwarf_info = None
        self.location_parser = None
        self.file_data = None
        self.symbols = {}
        self.added_items = set()
        self.data_tree = []

    # <editor-fold desc="文件操作">
    # 解析AXF文件函数
    def f_parseFileFunc(self):
        """
        function:  解析AXF文件函数
              in:  None
             out:  解析成功返回True，失败返回False
          return:  bool
          others:  Parse AXF File Func
        """
        try:
            with open(self.file_path, 'rb') as f:
                self.file_data = f.read()
                self.elf_file = ELFFile(f)

                # 检查是否有DWARF信息
                if not self.elf_file.has_dwarf_info():
                    return False

                # 获取DWARF信息
                self.dwarf_info = self.elf_file.get_dwarf_info()
                self.location_parser = LocationParser(self.dwarf_info.location_lists())

                # 解析符号表
                self.f_parseSymbolTableFunc()

                # 解析文件内容
                self.f_parseAxfContentFunc()
                return True
        except Exception as e:
            print(f"解析失败: {str(e)}")
            return False

    # </editor-fold>

    # <editor-fold desc="符号表操作">
    # 解析ELF符号表函数
    def f_parseSymbolTableFunc(self):
        """
        function:  解析ELF符号表函数
              in:  None
             out:  None
          return:  None
          others:  Parse ELF Symbol Table Func
        """
        self.symbols = {}
        section = self.elf_file.get_section_by_name('.symtab')
        if section is None:
            return

        for symbol in section.iter_symbols():
            if symbol['st_info']['type'] == 'STT_OBJECT':
                self.symbols[symbol.name] = {
                    'address': symbol['st_value'],
                    'size': symbol['st_size']
                }

    # </editor-fold>

    # <editor-fold desc="DWARF解析操作">
    # 解析AXF文件内容函数
    def f_parseAxfContentFunc(self):
        """
        function:  解析AXF文件内容函数
              in:  None
             out:  None
          return:  None
          others:  Parse AXF File Content Func
         """
        self.data_tree = []
        # 解析所有编译单元
        for cu in self.dwarf_info.iter_CUs():
            line_program = self.dwarf_info.line_program_for_CU(cu)
            file_name = line_program['file_entry'][0].name.decode('utf-8') if line_program else "Unknown"
            top_die = cu.get_top_DIE()
            self.f_processDieFunc(top_die, file_name, None)
        # self.added_items : 参数名称及地址的字典

    # 处理DWARF信息条目函数
    def f_processDieFunc(self, die, file_name, parent_node):
        """
        function:  处理DWARF信息条目函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
             out:  current_node: 当前节点
          return:  None
          others:  Process DWARF Information Entry Func
        """
        # 跳过编译单元DIE本身
        if die.tag == 'DW_TAG_compile_unit':
            for child in die.iter_children():
                self.f_processDieFunc(child, file_name, parent_node)
            return

        current_node = None

        if die.tag == 'DW_TAG_variable':
            current_node = self.f_processVariableFunc(die, file_name, parent_node)
        elif die.tag == 'DW_TAG_structure_type':
            current_node = self.f_processStructFunc(die, file_name, parent_node)
        elif die.tag == 'DW_TAG_array_type':
            current_node = self.f_processArrayFunc(die, file_name, parent_node)
        elif die.tag == 'DW_TAG_member':
            current_node = self.f_processMemberFunc(die, file_name, parent_node)
        elif die.tag == 'DW_TAG_typedef':
            current_node = self.f_processTypedefFunc(die, file_name, parent_node)
        elif die.tag == 'DW_TAG_subprogram':
            # 处理函数但不显示函数本身
            current_node = self.f_processFunctionFunc(die, file_name, parent_node)
            # 如果函数有成员变量，处理这些变量
            if current_node is None:
                for child in die.iter_children():
                    self.f_processFunctionChildFunc(child, file_name, parent_node, die)
                return None

        # 递归处理子节点
        for child in die.iter_children():
            self.f_processDieFunc(child, file_name, current_node if current_node else parent_node)

        return current_node

    # 处理函数内部的子节点函数
    def f_processFunctionChildFunc(self, die, file_name, parent_node, function_die):
        """
        function:  处理函数内部的子节点函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
                   function_die: 函数DIE
             out:  None
          return:  None
          others:  Process Function Inner Children
        """
        function_name_attr = function_die.attributes.get('DW_AT_name', None)
        function_name = function_name_attr.value.decode('utf-8') if function_name_attr else "Unknown"

        # 只处理变量类型的子节点
        if die.tag in ['DW_TAG_variable', 'DW_TAG_formal_parameter']:
            name_attr = die.attributes.get('DW_AT_name', None)
            if not name_attr:
                return

            var_name = name_attr.value.decode('utf-8')
            combined_name = f"{function_name}#{var_name}"

            # 获取类型信息
            type_die = self.f_getTypeDieFunc(die)
            type_name = self.f_getTypeNameFunc(type_die) if type_die else "unknown"

            # 获取地址
            address = self.symbols.get(var_name, {}).get('address', None)
            if address is None:
                address = self.f_getVariableAddressFunc(die)

            # 跳过地址为N/A的变量
            if address is None:
                return

            address_str = f"0x{address:08X}" if address is not None else "N/A"

            # 获取大小
            size = self.symbols.get(var_name, {}).get('size', None)
            if size is None and type_die:
                size = self.f_getTypeSizeFunc(type_die)
            size_str = str(size) if size else "N/A"

            # 是否指针
            is_pointer = "true" if type_die and type_die.tag == 'DW_TAG_pointer_type' else "false"

            # 指针偏移
            ptr_offset = "0"

            # 创建唯一标识符，防止重复
            item_id = f"{combined_name}|{address_str}"
            if item_id in self.added_items:
                return
            self.added_items.add(item_id)

            # 创建数据节点
            node = {
                'name': combined_name,
                'address': address_str,
                'size': size_str,
                'type': type_name,
                'location': file_name,
                'is_pointer': is_pointer,
                'ptr_offset': ptr_offset,
                'children': []
            }

            # 添加到树中
            if parent_node:
                parent_node['children'].append(node)
            else:
                self.data_tree.append(node)

            # 如果变量是结构体类型，添加其成员
            if type_die and type_die.tag == 'DW_TAG_structure_type' and address is not None:
                self.f_addStructureMembersFunc(type_die, file_name, node, address)
            # 新增：如果变量是数组类型，添加其元素
            elif type_die and type_die.tag == 'DW_TAG_array_type' and address is not None:
                self.f_addArrayElementsFunc(type_die, file_name, node, address)

    # 处理变量函数
    def f_processVariableFunc(self, die, file_name, parent_node):
        """
        function:  处理变量函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
             out:  node: 当前节点
          return:  None
          others:  Process Variable Func
        """
        name_attr = die.attributes.get('DW_AT_name', None)
        if not name_attr:
            return None

        name = name_attr.value.decode('utf-8')

        # 获取类型信息
        type_die = self.f_getTypeDieFunc(die)
        type_name = self.f_getTypeNameFunc(type_die) if type_die else "unknown"

        # 获取地址
        address = self.symbols.get(name, {}).get('address', None)
        if address is None:
            address = self.f_getVariableAddressFunc(die)

        # 跳过地址为N/A的变量
        if address is None:
            return None

        address_str = f"0x{address:08X}" if address is not None else "N/A"

        # 获取大小
        size = self.symbols.get(name, {}).get('size', None)
        if size is None and type_die:
            size = self.f_getTypeSizeFunc(type_die)
        size_str = str(size) if size else "N/A"

        # 是否指针
        is_pointer = "true" if type_die and type_die.tag == 'DW_TAG_pointer_type' else "false"

        # 指针偏移
        ptr_offset = "0"

        # 创建唯一标识符，防止重复
        item_id = f"{name}|{address_str}"
        if item_id in self.added_items:
            return None
        self.added_items.add(item_id)

        # 创建数据节点
        node = {
            'name': name,
            'address': address_str,
            'size': size_str,
            'type': type_name,
            'location': file_name,
            'is_pointer': is_pointer,
            'ptr_offset': ptr_offset,
            'children': []
        }

        # 添加到树中
        if parent_node:
            parent_node['children'].append(node)
        else:
            self.data_tree.append(node)

        # 如果变量是结构体类型，添加其成员
        if type_die and type_die.tag == 'DW_TAG_structure_type' and address is not None:
            self.f_addStructureMembersFunc(type_die, file_name, node, address)
        # 新增：如果变量是数组类型，添加其元素
        elif type_die and type_die.tag == 'DW_TAG_array_type' and address is not None:
            self.f_addArrayElementsFunc(type_die, file_name, node, address)

        return node

    # 为结构体变量添加成员函数
    def f_addStructureMembersFunc(self, struct_die, file_name, parent_node, base_address):
        """
        function:  为结构体变量添加成员函数
              in:  struct_die: 结构体DIE
                   file_name: 文件名
                   parent_node: 父节点
                   base_address: 基地址
             out:  None
          return:  None
          others:  Add Structure Members Func
        """
        current_offset = 0

        # 获取结构体对齐要求
        struct_alignment = 1
        align_attr = struct_die.attributes.get('DW_AT_alignment', None)
        if align_attr:
            struct_alignment = align_attr.value

        for child in struct_die.iter_children():
            if child.tag == 'DW_TAG_member':
                # 获取成员对齐要求
                member_alignment = 1
                type_die = self.f_getTypeDieFunc(child)
                if type_die:
                    member_alignment = self.f_getTypeAlignment(type_die) or 1

                # 计算对齐填充
                padding = 0
                if member_alignment > 1:
                    padding = (member_alignment - (current_offset % member_alignment)) % member_alignment
                current_offset += padding

                # 处理成员
                member_node = self.f_processMemberFunc(child, file_name, parent_node, base_address + current_offset)

                # 更新偏移量
                if member_node:
                    member_size = int(member_node['size']) if member_node['size'] != "N/A" else 0
                    current_offset += member_size

    # 为数组变量添加元素函数
    def f_addArrayElementsFunc(self, array_die, file_name, parent_node, base_address):
        """
        function:  为数组变量添加元素函数
              in:  array_die: 数组DIE
                   file_name: 文件名
                   parent_node: 父节点
                   base_address: 基地址
             out:  None
          return:  None
          others:  Add Array Elements Func
        """
        element_type_die = self.f_getTypeDieFunc(array_die)
        if not element_type_die:
            return

        element_size = self.f_getTypeSizeFunc(element_type_die) or 0

        # 获取数组维度信息 - 修复：处理所有子范围
        dimensions = []
        for child in array_die.iter_children():
            if child.tag == 'DW_TAG_subrange_type':
                count_attr = child.attributes.get('DW_AT_count', None)
                if count_attr:
                    dimensions.append(count_attr.value)
                    continue

                upper_attr = child.attributes.get('DW_AT_upper_bound', None)
                lower_attr = child.attributes.get('DW_AT_lower_bound', None)
                if upper_attr is not None and lower_attr is not None:
                    dimensions.append(upper_attr.value - lower_attr.value + 1)
                elif upper_attr is not None:  # 处理只有上界的情况
                    dimensions.append(upper_attr.value + 1)  # 下界默认为0

        # 计算总元素数 - 修复：处理多维数组
        total_elements = 1
        for dim in dimensions:
            total_elements *= dim

        # 添加数组元素 - 修复：正确计算元素地址
        for i in range(total_elements):
            element_address = base_address + i * element_size
            element_name = f"[{i}]"
            element_address_str = f"0x{element_address:08X}"

            # 创建唯一标识符，防止重复
            item_id = f"{parent_node['name']}{element_name}|{element_address_str}"
            if item_id in self.added_items:
                continue
            self.added_items.add(item_id)

            # 创建数组元素节点
            element_node = {
                'name': element_name,
                'address': element_address_str,
                'size': str(element_size),
                'type': self.f_getTypeNameFunc(element_type_die),
                'location': file_name,
                'is_pointer': "false",
                'ptr_offset': "0",
                'children': []
            }
            parent_node['children'].append(element_node)

            # 如果元素是结构体，递归添加成员
            if element_type_die.tag == 'DW_TAG_structure_type':
                self.f_addStructureMembersFunc(
                    element_type_die,
                    file_name,
                    element_node,
                    element_address
                )
            # 新增：处理基本类型数组的元素类型
            elif element_type_die.tag == 'DW_TAG_array_type':
                # 递归处理多维数组
                self.f_addArrayElementsFunc(
                    element_type_die,
                    file_name,
                    element_node,
                    element_address
                )

    # 处理结构体定义函数
    def f_processStructFunc(self, die, file_name, parent_node):
        """
        function:  处理结构体定义函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
             out:  node: 当前节点
          return:  None
          others:  Process Structure Definition Func
        """
        name_attr = die.attributes.get('DW_AT_name', None)
        if not name_attr:
            return None

        name = name_attr.value.decode('utf-8')

        # 获取大小
        size_attr = die.attributes.get('DW_AT_byte_size', None)
        size = size_attr.value if size_attr else 0

        # 创建数据节点
        node = {
            'name': name,
            'address': "N/A",
            'size': str(size),
            'type': f"struct {name}",
            'location': file_name,
            'is_pointer': "false",
            'ptr_offset': "0",
            'children': []
        }

        # 跳过地址为N/A的顶层节点
        if parent_node is None:
            return None

        # 添加到树中
        if parent_node:
            parent_node['children'].append(node)
        else:
            self.data_tree.append(node)

        return node

    # 处理数组定义函数
    def f_processArrayFunc(self, die, file_name, parent_node):
        """
        function:  处理数组定义函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
             out:  node: 当前节点
          return:  None
          others:  Process Array Definition Func
        """
        type_die = self.f_getTypeDieFunc(die)
        type_name = self.f_getTypeNameFunc(type_die) if type_die else "unknown"

        # 获取数组维度信息 - 修复：处理所有维度
        dimensions = []
        for child in die.iter_children():
            if child.tag == 'DW_TAG_subrange_type':
                count_attr = child.attributes.get('DW_AT_count', None)
                if count_attr:
                    dimensions.append(count_attr.value)
                    continue

                upper_attr = child.attributes.get('DW_AT_upper_bound', None)
                lower_attr = child.attributes.get('DW_AT_lower_bound', None)
                if upper_attr is not None and lower_attr is not None:
                    dimensions.append(upper_attr.value - lower_attr.value + 1)
                elif upper_attr is not None:  # 处理只有上界的情况
                    dimensions.append(upper_attr.value + 1)  # 下界默认为0

        # 计算数组元素总数
        array_element_count = 1
        for dim in dimensions:
            array_element_count *= dim

        # 获取元素大小
        element_size = self.f_getTypeSizeFunc(type_die) if type_die else 0
        total_size = array_element_count * element_size if element_size else 0

        # 获取名称 - 修复：显示多维数组
        dim_str = "][".join(str(dim) for dim in dimensions)
        name = f"array[{dim_str}] of {type_name}"

        # 创建数据节点
        node = {
            'name': name,
            'address': "N/A",
            'size': str(total_size),
            'type': name,
            'location': file_name,
            'is_pointer': "false",
            'ptr_offset': "0",
            'children': []
        }

        # 跳过地址为N/A的顶层节点
        if parent_node is None:
            return None

        # 添加到树中
        if parent_node:
            parent_node['children'].append(node)
        else:
            self.data_tree.append(node)

        return node

    # 处理结构体成员函数
    def f_processMemberFunc(self, die, file_name, parent_node, base_address=None):
        """
        function:  处理结构体成员函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
                   base_address: 基地址
             out:  node: 当前节点
          return:  None
          others:  Process Structure Member Func
        """
        if not parent_node:
            return None

        name_attr = die.attributes.get('DW_AT_name', None)
        if not name_attr:
            return None

        name = name_attr.value.decode('utf-8')

        # 获取类型
        type_die = self.f_getTypeDieFunc(die)
        type_name = self.f_getTypeNameFunc(type_die) if type_die else "unknown"

        # 增强的偏移量解析
        offset = 0
        location_attr = die.attributes.get('DW_AT_data_member_location', None)
        if location_attr:
            # 处理直接偏移值
            if location_attr.form in ['DW_FORM_data1', 'DW_FORM_data2',
                                      'DW_FORM_data4', 'DW_FORM_data8',
                                      'DW_FORM_udata', 'DW_FORM_sdata']:
                offset = location_attr.value

            # 处理表达式位置
            elif location_attr.form == 'DW_FORM_exprloc':
                expr = location_attr.value
                if expr:
                    # DW_OP_plus_uconst
                    if expr[0] == 0x23:
                        # 解码ULEB128
                        value = 0
                        shift = 0
                        for byte in expr[1:]:
                            value |= (byte & 0x7F) << shift
                            if not (byte & 0x80):
                                break
                            shift += 7
                        offset = value

                    # DW_OP_constu + DW_OP_plus
                    elif len(expr) >= 2 and expr[0] == 0x10:  # DW_OP_constu
                        # 解码ULEB128
                        const_val = 0
                        shift = 0
                        idx = 1
                        while idx < len(expr):
                            byte = expr[idx]
                            const_val |= (byte & 0x7F) << shift
                            shift += 7
                            idx += 1
                            if not (byte & 0x80):
                                break

                        # 检查后续操作
                        if idx < len(expr) and expr[idx] == 0x22:  # DW_OP_plus
                            offset = const_val

        # 计算成员地址
        if base_address is not None:
            address = base_address + offset
            address_str = f"0x{address:08X}"
        else:
            address_str = f"+{offset}"

        # 获取大小
        size = self.f_getTypeSizeFunc(type_die) if type_die else 0

        # 创建唯一标识符，防止重复
        item_id = f"{parent_node['name']}.{name}|{address_str}"
        if item_id in self.added_items:
            return None
        self.added_items.add(item_id)

        # 创建数据节点
        node = {
            'name': name,
            'address': address_str,
            'size': str(size),
            'type': type_name,
            'location': file_name,
            'is_pointer': "false",
            'ptr_offset': "0",
            'children': []
        }

        # 添加到父节点
        parent_node['children'].append(node)

        # 如果成员本身是结构体，递归添加其成员
        if type_die and type_die.tag == 'DW_TAG_structure_type' and base_address is not None:
            self.f_addStructureMembersFunc(type_die, file_name, node, address)
        # 新增：如果成员是数组类型，递归添加其元素
        elif type_die and type_die.tag == 'DW_TAG_array_type' and base_address is not None:
            self.f_addArrayElementsFunc(type_die, file_name, node, address)

        return node

    # 处理typedef定义函数
    def f_processTypedefFunc(self, die, file_name, parent_node):
        """
        function:  处理typedef定义函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
             out:  node: 当前节点
          return:  None
          others:  Process Typedef Definition Func
        """
        name_attr = die.attributes.get('DW_AT_name', None)
        if not name_attr:
            return None

        name = name_attr.value.decode('utf-8')

        # 获取基础类型
        type_die = self.f_getTypeDieFunc(die)
        type_name = self.f_getTypeNameFunc(type_die) if type_die else "unknown"

        # 创建数据节点
        node = {
            'name': name,
            'address': "N/A",
            'size': "",
            'type': type_name,
            'location': file_name,
            'is_pointer': "false",
            'ptr_offset': "0",
            'children': []
        }

        # 跳过地址为N/A的顶层节点
        if parent_node is None:
            return None

        # 添加到树中
        if parent_node:
            parent_node['children'].append(node)
        else:
            self.data_tree.append(node)

        return node

    # 处理函数定义函数
    def f_processFunctionFunc(self, die, file_name, parent_node):
        """
        function:  处理函数定义函数
              in:  die: DWARF信息条目
                   file_name: 文件名
                   parent_node: 父节点
             out:  None
          return:  总是返回None（不显示函数节点）
          others:  Process Function Definition Func
        """
        return None

    # 添加类型对齐要求获取函数
    def f_getTypeAlignment(self, die):
        """获取类型对齐要求"""
        # 基本类型对齐
        if die.tag == 'DW_TAG_base_type':
            size = self.f_getTypeSizeFunc(die) or 1
            return min(size, 8)  # 最大对齐为8字节

        # 指针类型对齐
        if die.tag == 'DW_TAG_pointer_type':
            return self.elf_file.elfclass // 8  # 4或8字节

        # 结构体/联合体对齐
        if die.tag in ['DW_TAG_structure_type', 'DW_TAG_union_type']:
            align_attr = die.attributes.get('DW_AT_alignment', None)
            if align_attr:
                return align_attr.value

            # 计算成员最大对齐
            max_alignment = 1
            for child in die.iter_children():
                if child.tag == 'DW_TAG_member':
                    child_type = self.f_getTypeDieFunc(child)
                    if child_type:
                        alignment = self.f_getTypeAlignment(child_type) or 1
                        max_alignment = max(max_alignment, alignment)
            return max_alignment

        # 数组类型使用元素对齐
        if die.tag == 'DW_TAG_array_type':
            element_type = self.f_getTypeDieFunc(die)
            return self.f_getTypeAlignment(element_type) if element_type else 1

        # 默认情况
        return 1

    # </editor-fold>

    # <editor-fold desc="类型操作">
    # 获取变量的类型DIE函数
    @staticmethod
    def f_getTypeDieFunc(die):
        """
        function:  获取变量的类型DIE函数
              in:  die: DWARF信息条目
             out:  type_die: 类型DIE
          return:  None
          others:  Get Variable Type DIE Func
        """
        type_attr = die.attributes.get('DW_AT_type', None)
        if not type_attr:
            return None

        type_die = die.get_DIE_from_attribute('DW_AT_type')
        if not type_die:
            return None

        # 处理typedef、const和volatile
        while type_die and type_die.tag in ['DW_TAG_typedef',
                                            'DW_TAG_const_type',
                                            'DW_TAG_volatile_type']:
            type_attr = type_die.attributes.get('DW_AT_type', None)
            if not type_attr:
                return type_die
            type_die = type_die.get_DIE_from_attribute('DW_AT_type')

        return type_die

    # 获取类型名称函数
    def f_getTypeNameFunc(self, die):
        """
        function:  获取类型名称函数
              in:  die: DWARF信息条目
             out:  die.tag: 类型名称
          return:  None
          others:  Get Type Name Func
        """
        if die is None:
            return "unknown"

        if die.tag == 'DW_TAG_base_type':
            name_attr = die.attributes.get('DW_AT_name', None)
            return name_attr.value.decode('utf-8') if name_attr else "base_type"
        elif die.tag == 'DW_TAG_structure_type':
            name_attr = die.attributes.get('DW_AT_name', None)
            return name_attr.value.decode('utf-8') if name_attr else "struct"
        elif die.tag == 'DW_TAG_array_type':
            element_type = self.f_getTypeDieFunc(die)
            if element_type:
                return f"array of {self.f_getTypeNameFunc(element_type)}"
            return "array"
        elif die.tag == 'DW_TAG_pointer_type':
            pointed_type = self.f_getTypeDieFunc(die)
            if pointed_type:
                return f"pointer to {self.f_getTypeNameFunc(pointed_type)}"
            return "pointer"
        elif die.tag == 'DW_TAG_const_type':
            const_type = self.f_getTypeDieFunc(die)
            if const_type:
                return f"const {self.f_getTypeNameFunc(const_type)}"
            return "const"
        elif die.tag == 'DW_TAG_typedef':
            name_attr = die.attributes.get('DW_AT_name', None)
            return name_attr.value.decode('utf-8') if name_attr else "typedef"
        elif die.tag == 'DW_TAG_union_type':
            name_attr = die.attributes.get('DW_AT_name', None)
            return name_attr.value.decode('utf-8') if name_attr else "union"
        return die.tag

    # 获取类型大小函数
    def f_getTypeSizeFunc(self, die):
        """
        function:  获取类型大小函数
              in:  die: DWARF信息条目
             out:  类型大小
          return:  int
          others:  Get Type Size Func
        """
        if die is None:
            return 0

        # 检查是否有直接的大小属性
        size_attr = die.attributes.get('DW_AT_byte_size', None)
        if size_attr:
            return size_attr.value

        # 处理指针类型
        if die.tag == 'DW_TAG_pointer_type':
            return self.elf_file.elfclass // 8  # 4 for 32-bit, 8 for 64-bit

        # 处理数组类型 - 修复：正确处理多维数组
        if die.tag == 'DW_TAG_array_type':
            element_type = self.f_getTypeDieFunc(die)
            element_size = self.f_getTypeSizeFunc(element_type) if element_type else 0

            # 查找所有子范围以获取数组大小（多维数组）
            array_element_count = 1
            for child in die.iter_children():
                if child.tag == 'DW_TAG_subrange_type':
                    count_attr = child.attributes.get('DW_AT_count', None)
                    if count_attr:
                        array_element_count *= count_attr.value
                        continue

                    upper_attr = child.attributes.get('DW_AT_upper_bound', None)
                    lower_attr = child.attributes.get('DW_AT_lower_bound', None)
                    if upper_attr is not None and lower_attr is not None:
                        array_element_count *= (upper_attr.value - lower_attr.value + 1)
                    elif upper_attr is not None:  # 处理只有上界的情况
                        array_element_count *= (upper_attr.value + 1)  # 下界默认为0

            return element_size * array_element_count

        # 处理volatile类型 - 递归获取基础类型的大小
        if die.tag == 'DW_TAG_volatile_type':
            base_type = self.f_getTypeDieFunc(die)
            if base_type:
                return self.f_getTypeSizeFunc(base_type)
            return 0

        # 处理结构体类型 - 计算所有成员的大小
        if die.tag == 'DW_TAG_structure_type':
            total_size = 0
            current_offset = 0

            # 获取结构体对齐要求
            struct_alignment = self.f_getTypeAlignment(die) or 1

            for child in die.iter_children():
                if child.tag == 'DW_TAG_member':
                    # 获取成员类型
                    member_type = self.f_getTypeDieFunc(child)
                    if not member_type:
                        continue

                    # 获取成员大小和对齐
                    member_size = self.f_getTypeSizeFunc(member_type)
                    member_alignment = self.f_getTypeAlignment(member_type) or 1

                    # 计算对齐填充
                    padding = (member_alignment - (current_offset % member_alignment)) % member_alignment
                    current_offset += padding
                    total_size += padding

                    # 添加成员大小
                    current_offset += member_size
                    total_size += member_size

            # 结构体尾部填充
            if total_size % struct_alignment != 0:
                padding = struct_alignment - (total_size % struct_alignment)
                total_size += padding

            return total_size

        return 0

    # </editor-fold>

    # <editor-fold desc="地址操作">
    # 获取变量地址函数
    def f_getVariableAddressFunc(self, die):
        """
        function:  获取变量地址函数
              in:  die: DWARF信息条目
             out:  变量地址
          return:  struct
          others:  Get Variable Address Func
        """
        # 1. 尝试从位置属性获取
        location_attr = die.attributes.get('DW_AT_location', None)
        if location_attr:
            # 处理表达式位置
            if location_attr.form == 'DW_FORM_exprloc':
                expr = location_attr.value
                if expr and expr[0] == 0x03:  # DW_OP_addr
                    addr_size = len(expr) - 1
                    addr_bytes = expr[1:1 + addr_size]
                    if addr_size == 4:
                        return struct.unpack('<I', addr_bytes)[0]
                    elif addr_size == 8:
                        return struct.unpack('<Q', addr_bytes)[0]

            # 处理位置列表
            elif location_attr.form == 'DW_FORM_sec_offset':
                loc_list = self.location_parser.parse_from_attribute(location_attr, die.cu['version'])
                if loc_list and loc_list[0].loc_expr:
                    expr = loc_list[0].loc_expr
                    if expr and expr[0] == 0x03:  # DW_OP_addr
                        addr_size = len(expr) - 1
                        addr_bytes = expr[1:1 + addr_size]
                        if addr_size == 4:
                            return struct.unpack('<I', addr_bytes)[0]
                        elif addr_size == 8:
                            return struct.unpack('<Q', addr_bytes)[0]

        # 2. 尝试从PC属性获取
        if 'DW_AT_low_pc' in die.attributes:
            return die.attributes['DW_AT_low_pc'].value

        # 3. 尝试从符号表获取（通过名称）
        name_attr = die.attributes.get('DW_AT_name', None)
        if name_attr:
            name = name_attr.value.decode('utf-8')
            if name in self.symbols:
                return self.symbols[name]['address']

        return None

    # </editor-fold>

    # <editor-fold desc="数据访问">
    def f_getDataTreeFunc(self):
        """
        function:  获取解析后的数据树函数
              in:  None
             out:  self.data_tree:数据树
          return:  list
          others:  Get parsed data tree
        """
        return self.data_tree

    # 获取文件原始数据函数
    def f_getFileDataFunc(self):
        """
        function:  获取文件原始数据函数
              in:  None
             out:  self.file_data:文件原始数据
          return:  None
          others:  Get Raw File Data Func
        """
        return self.file_data
    # </editor-fold>
